/**
 * 雪球期权子表
 */
import React, { PureComponent } from 'react';
import _ from 'lodash';
import { CloseOutlined, PlusCircleOutlined, PlusCircleTwoTone } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, message } from 'antd';
import { SelectC, InputNumberC } from '../../../../comps';
import { connect } from 'dva';
import { config1, dict } from '../config';
import shareOptionStyle from '../shareOptionStyle.less';
import moment from 'moment';
@Form.create()
@connect(({ shareOptionManageM, bookM, globalM }) => ({ shareOptionManageM, bookM, globalM }))
export default class BookSnowball extends PureComponent {
  state = {
    koObservationDateTemp: undefined, // 敲出_观察序列
    koObservationDate: [], // 添加的敲出_观察序列
    koBarrierRate: undefined, // 敲出_障碍价格率
  };
  componentDidMount() {
    this.props.onRef(this);
    const { bookSnowball } = this.props;
    if (bookSnowball.koObservationDate && bookSnowball.koBarrierRate && bookSnowball.koBarrier) {
      const newkoObservationDate = this.changekoObservationDate(bookSnowball);
      this.setState({
        koObservationDate: newkoObservationDate,
      });
    }
  }

  // 改变敲出_观察序列数据结构
  changekoObservationDate = (bookSnowball) => {
    let koObservationDate = bookSnowball.koObservationDate.split(',');
    let koBarrierRate = bookSnowball.koBarrierRate.split(',');
    let koBarrier = bookSnowball.koBarrier.split(',');
    let newkoObservationDate = [];
    for (var i = 0; i < koObservationDate.length; i++) {
      newkoObservationDate.push({ temp: koObservationDate[i], koBarrierRate: koBarrierRate[i], koBarrier: koBarrier[i] });
    }
    return newkoObservationDate;
  };
  // 获取表单数据
  getSettingInfo = () => {
    const {
      form: { validateFieldsAndScroll },
    } = this.props;
    const { koObservationDate } = this.state;
    let result = undefined;
    validateFieldsAndScroll((error, values) => {
      if (error) {
        return false;
      } else {
        if (koObservationDate.length > 0) {
          let koObservationDate1 = [];
          let koBarrierRate = [];
          let koBarrier = [];
          koObservationDate.map((item) => {
            koObservationDate1.push(item.temp), koBarrierRate.push(item.koBarrierRate), koBarrier.push(item.koBarrier);
          });
          let vo = {
            ...values,
            koObservationDate: koObservationDate1.join(),
            koBarrierRate: koBarrierRate.join(),
            koBarrier: koBarrier.join(),
          };
          result = vo;
        } else {
          return;
        }
      }
    });
    return result;
  };
  // 敲出_观察序列新增
  addTime = () => {
    const { koObservationDateTemp, koObservationDate, koBarrierRate } = this.state;
    const { initialPrice } = this.props;
    if (koBarrierRate < 0) {
      message.error('敲出价格障碍率必须大于0');
      return;
    }
    if (!initialPrice) {
      message.error('请先填写期初价格');
      this.resetTrigger();
    } else {
      let temp = koObservationDateTemp ? koObservationDateTemp.format('YYYY-MM-DD') : undefined;
      let koBarrier = ((initialPrice * koBarrierRate) / 100).toFixed(2);
      let vo = _.cloneDeep(koObservationDate);
      if (temp && koBarrierRate) {
        if (!vo.some((item) => item.temp == temp)) {
          vo.unshift({ temp, koBarrierRate, koBarrier });
          this.setState({
            koObservationDate: vo,
            koObservationDateTemp: '',
          });
          this.props.form.setFieldsValue({
            koBarrierRate: undefined,
          });
        } else {
          message.error('时间已存在');
        }
      } else {
        message.error('请填写完整的信息');
      }
    }
  };
  // 敲出_观察序列改变
  koObservationDateChange = (e) => {
    this.setState({
      koObservationDateTemp: e,
    });
  };
  // 敲出_观察序列删除
  koObservationDateDel = (index) => {
    const vo = _.cloneDeep(this.state.koObservationDate);
    vo.splice(index, 1);
    this.setState({
      koObservationDate: vo,
    });
  };

  // 对敲入_障碍价格和敲入_障碍价格率改变
  onChange = (params) => {
    const {
      initialPrice,
      form: { setFieldsValue },
    } = this.props;
    const { key, e } = params;
    if (!initialPrice) {
      message.error('请先填写期初价格');
      this.resetTrigger();
    } else {
      if (key === 'kiBarrierRate') {
        // 计算敲入_障碍价格
        if (e) {
          setFieldsValue({
            kiBarrier: ((e / 100) * initialPrice).toFixed(2),
          });
        } else {
          setFieldsValue({
            kiBarrier: undefined,
          });
        }
      }
      if (key === 'kiBarrier') {
        // 计算敲入_障碍价格率
        if (e) {
          setFieldsValue({
            kiBarrierRate: ((e / initialPrice) * 100).toFixed(2),
          });
        } else {
          setFieldsValue({
            kiBarrierRate: undefined,
          });
        }
      }
    }
  };

  // 响应敲出_障碍价格率
  koBarrierChange = (e) => {
    const { initialPrice } = this.props;
    if (!initialPrice) {
      message.error('请先填写期初价格');
      this.resetTrigger();
    } else {
      this.setState({ koBarrierRate: e });
    }
  };
  // 表单重置
  resetForm = () => {
    this.props.form.resetFields();
    this.setState({
      koObservationDate: [],
      koObservationDateTemp: undefined,
    });
  };
  // 当baseOption组件里期初价格变化则敲入_障碍价格和敲入_障碍价格率重填
  resetTrigger = (e) => {
    const { koObservationDate } = this.state;
    const { initialPrice } = this.props;
    this.props.form.setFieldsValue({
      kiBarrierRate: undefined,
      kiBarrier: undefined,
      koBarrier: undefined,
      koBarrierRate: undefined,
    });
    if (e) {
      koObservationDate.map((item) => (item.koBarrier = ((item.koBarrierRate * e) / 100).toFixed(2)));
    } else {
      koObservationDate.map((item) => (item.koBarrier = '--'));
    }

    this.setState({
      koObservationDate: koObservationDate,
    });
  };
  // 禁选日期设定
  disabledDate = (value) => {
    const { beginDate, endDate } = this.props;
    // 全部禁用传null
    if (beginDate === null && endDate === null) return true;
    let valueF = value.format('YYYYMMDD');
    let disBeginF = beginDate === '' || beginDate === undefined ? '' : beginDate.format('YYYYMMDD') - '01';
    let disEndF = endDate === '' || endDate === undefined ? moment().format('YYYYMMDD') : endDate.format('YYYYMMDD') + '01';

    if (endDate === '' || endDate === undefined) {
      return valueF <= disBeginF;
    } else {
      return valueF <= disBeginF || valueF >= disEndF;
    }
  };
  render() {
    const {
      bookSnowball,
      structure,
      bookM: { onlyView },
      globalM: { dataDictionary: dictionary },
    } = this.props;
    const { koObservationDate } = this.state;
    const { info } = config1[4]; // 配置文件中 雪球期权的标题配置
    // 整个组件是否可填写
    const disabledImportant = onlyView || (structure == '4' ? false : true);
    // 生成InputNumber
    const generateInputNumber = ({ key, unit, onChange, precision, disabled }) => {
      return (
        <div style={{ width: '100%', height: '39px', marginBottom: info[key].space }}>
          <InputNumberC
            form={this.props.form}
            dataIndex={key}
            disabled={disabledImportant || info[key].isGrey || disabled}
            unit={unit}
            precision={precision}
            initialValue={bookSnowball[key]}
            onChange={
              onChange
                ? (e) => {
                    onChange({ key, e });
                  }
                : undefined
            }
            rules={[{ required: info[key].isRequired, message: '此为必填项' }]}
          />
        </div>
      );
    };
    // 普通的select
    const generateSelect = ({ key, data, isRequired, onChange, defaultdate }) => {
      let dictArr = [];
      if (dict[key] && dictionary[dict[key]]) {
        dictArr = dictionary[dict[key]].map((item) => {
          return { title: item.value, value: item.code };
        });
      }
      let arr = data || dictArr || [];
      return (
        <div style={{ width: '100%', height: '39px', marginBottom: info[key].space }}>
          <SelectC
            style={{ width: '100%', height: '100%' }}
            dataIndex={key}
            form={this.props.form}
            dataSource={arr}
            placeholder=''
            onChange={
              onChange
                ? (e) => {
                    onChange(e);
                  }
                : undefined
            }
            disabled={disabledImportant || info[key].isGrey}
            initialValue={bookSnowball[key] ? bookSnowball[key] : defaultdate ? defaultdate : null}
            rules={[{ required: isRequired ? true : info[key].isRequired, message: '此为必填项' }]}
            positionBody={true}
          />
        </div>
      );
    };

    return (
      <div className={shareOptionStyle.bookBarrier}>
        {/* 敲入_观察频率 */}
        {generateSelect({ key: 'kiBarrierDuration', defaultdate: '1' })}
        {/* 敲入方向 */}
        {generateSelect({ key: 'kiDirection' })}
        {/* 敲入_障碍价格率（%） */}
        {generateInputNumber({ key: 'kiBarrierRate', unit: '%', precision: 2, onChange: this.onChange, unit: '%' })}
        {/* 敲入_障碍价格 */}
        {generateInputNumber({ key: 'kiBarrier', precision: 2, onChange: this.onChange })}
        {/* 敲出_观察频率 */}
        {generateSelect({ key: 'koBarrierDuration', defaultdate: '1', unit: '%' })}
        {/* 敲出_观察序列 */}
        <div className='observationDate'>
          <div className='dateDiv'>
            <div style={{ width: '200px' }} className='dataDiv'>
              <div style={{ width: '100px' }}>
                <DatePicker
                  style={{ width: '100%' }}
                  value={this.state.koObservationDateTemp}
                  onChange={this.koObservationDateChange}
                  disabled={disabledImportant}
                  format={'YYYY-MM-DD'}
                  disabledDate={this.disabledDate}
                />
              </div>
              <div style={{ width: '90px' }}>
                <InputNumberC
                  form={this.props.form}
                  dataIndex={'koBarrierRate'}
                  disabled={disabledImportant}
                  unit={'%'}
                  precision={2}
                  onChange={(e) => {
                    this.koBarrierChange(e);
                  }}
                  rules={[{ pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '必须大于0' }]}
                />
              </div>
            </div>
            <div style={{ width: '16px' }}>
              <a onClick={this.addTime}>{disabledImportant ? <PlusCircleOutlined style={{ width: '100%' }} /> : <PlusCircleTwoTone style={{ width: '100%' }} />}</a>
            </div>
          </div>
          <ul className={disabledImportant ? ' listDiv disabled' : 'listDiv'}>
            {koObservationDate.map((item, index) => (
              <li key={'koObservationDate_' + index}>
                <p className={'dataP'} title={item.temp}>
                  {item.temp}
                </p>
                <p style={{ marginLeft: '7px', marginRight: '7px' }}>{item.koBarrierRate + '%'}</p>
                <p>{item.koBarrier}</p>
                <a onClick={() => this.koObservationDateDel(index)}>
                  <CloseOutlined />
                </a>
              </li>
            ))}
          </ul>
        </div>
        {/* 敲出方向 */}
        {generateSelect({ key: 'koDirection' })}
        {/* 敲出收益率（%) */}
        {generateInputNumber({ key: 'rebate', unit: '%', precision: 2 })}
        {/* 结算方式 */}
        {generateSelect({ key: 'settleMode' })}
      </div>
    );
  }
}
